package com.orangeforms.webadmin.upms.service.impl;

import com.github.pagehelper.Page;
import com.orangeforms.common.core.base.dao.BaseDaoMapper;
import com.orangeforms.common.core.base.service.BaseService;
import com.orangeforms.common.core.object.MyRelationParam;
import com.orangeforms.common.core.util.MyDateUtil;
import com.orangeforms.webadmin.upms.dao.BusinessCollectionMapper;
import com.orangeforms.webadmin.upms.model.BusinessCollection;
import com.orangeforms.webadmin.upms.service.BusinessCollectionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.*;

/**
 * @Author：howlrou
 * @Date：2024/8/2 14:51
 */
@Slf4j
@Service("businessCollectionService")
public class BusinessCollectionServiceImpl extends BaseService<BusinessCollection, Long>
        implements BusinessCollectionService {

    @Autowired
    private BusinessCollectionMapper businessCollectionMapper;


    /**
     * 返回当前Service的主表Mapper对象。
     *
     * @return 主表Mapper对象。
     */
    @Override
    protected BaseDaoMapper<BusinessCollection> mapper() {
        return businessCollectionMapper;
    }


    /**
     * 获取过滤后的藏品列表。
     *
     * @param filter  主表过滤对象。
     * @param orderBy 排序字符串，order by从句的参数。
     * @return 对象列表。
     */
    @Override
    public List<BusinessCollection> getBusinessCollectionList(BusinessCollection filter, String orderBy) {
        List<BusinessCollection> resultList = businessCollectionMapper.selectBusinessCollectionList(filter, orderBy);
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }

    /**
     * 查询藏品详情
     *
     * @param collectionId 藏品详情主键
     * @return 藏品详情
     */
    @Override
    public BusinessCollection selectBusinessCollectionByCollectionId(Long collectionId) {
        return businessCollectionMapper.selectBusinessCollectionByCollectionId(collectionId);
    }

    /**
     * 查询藏品详情列表
     *
     * @param businessCollection 藏品详情
     * @return 藏品详情
     */
    @Override
    public List<BusinessCollection> selectBusinessCollectionList(BusinessCollection businessCollection) {
//        return businessCollectionMapper.selectBusinessCollectionList(businessCollection);
        return null;
    }

    /**
     * 新增藏品详情
     *
     * @param businessCollection 藏品详情
     * @return 结果
     */
    @Override
    public int insertBusinessCollection(BusinessCollection businessCollection) {
        businessCollection.setCreateTime(MyDateUtil.getNowDate());
        return businessCollectionMapper.insertBusinessCollection(businessCollection);
    }

    /**
     * 修改藏品详情
     *
     * @param businessCollection 藏品详情
     * @return 结果
     */
    @Override
    public int updateBusinessCollection(BusinessCollection businessCollection) {
        businessCollection.setUpdateTime(MyDateUtil.getNowDate());
        return businessCollectionMapper.updateBusinessCollection(businessCollection);
    }

    /**
     * 批量删除藏品详情
     *
     * @param collectionIds 需要删除的藏品详情主键
     * @return 结果
     */
    @Override
    public int deleteBusinessCollectionByCollectionIds(Long[] collectionIds) {
        return businessCollectionMapper.deleteBusinessCollectionByCollectionIds(collectionIds);
    }

    /**
     * 删除藏品详情信息
     *
     * @param collectionId 藏品详情主键
     * @return 结果
     */
    @Override
    public int deleteBusinessCollectionByCollectionId(Long collectionId) {
        return businessCollectionMapper.deleteBusinessCollectionByCollectionId(collectionId);
    }

    /**
     * 插入Excel表格数据
     *
     * @param file
     * @throws Exception
     */
    @Override
    public void saveExcelData(MultipartFile file) throws Exception {
        List<BusinessCollection> data = readExcel(file.getInputStream());
        this.saveBatch(data);
    }


    @Override
    public List<BusinessCollection> readExcelData(MultipartFile file) throws Exception {
        List<BusinessCollection> data = readExcel(file.getInputStream());
        return data;
    }

    private List<BusinessCollection> readExcel(InputStream is) throws Exception {
        List<BusinessCollection> data = new ArrayList<>();
        Workbook workbook = new XSSFWorkbook(is);
        Sheet sheet = workbook.getSheetAt(0);

        // 读取表头
        Row headerRow = sheet.getRow(0);
        Map<Integer, String> headerMap = new HashMap<>();
        for (Cell cell : headerRow) {
            headerMap.put(cell.getColumnIndex(), cell.getStringCellValue());
        }

        // 读取数据行，数据第一行为添加读取表头，第二行为中文表头，第三行开始为正式数据
        for (int i = 2; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            BusinessCollection collection = new BusinessCollection();

            for (Cell cell : row) {
                String header = headerMap.get(cell.getColumnIndex());
                if (header != null) {
                    setFieldValue(collection, header, cell);
                }
            }
            data.add(collection);
        }

        workbook.close();
        return data;
    }

    private void setFieldValue(BusinessCollection collection, String header, Cell cell) throws Exception {
        // 排除 collectionId 字段的处理
        if ("collectionId".equals(header)) {
            return;
        }
        Field field = BusinessCollection.class.getDeclaredField(header);
        field.setAccessible(true);

        switch (cell.getCellType()) {
            case STRING:
                field.set(collection, cell.getStringCellValue());
                break;
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    field.set(collection, cell.getDateCellValue());
                } else {
                    if (field.getType() == Integer.class) {
                        field.set(collection, (int) cell.getNumericCellValue());
                    } else if (field.getType() == Double.class) {
                        field.set(collection, cell.getNumericCellValue());
                    } else if (field.getType() == String.class) {
                        if (cell.getNumericCellValue() == (int) cell.getNumericCellValue()) {
                            field.set(collection, Integer.toString((int) cell.getNumericCellValue()));
                        } else {
                            field.set(collection, Double.toString(cell.getNumericCellValue()));
                        }
                    } else {
                        field.set(collection, cell.getNumericCellValue());
                    }
                }
                break;
            case BOOLEAN:
                field.set(collection, cell.getBooleanCellValue());
                break;
            default:
                field.set(collection, null);
        }
    }
}
